package isssr.bean.boundary;

import isssr.bean.control.UserManagement;
import isssr.bean.entity.User;
import isssr.bean.exception.AdminManagementException;

import java.io.Serializable;
import java.util.ArrayList;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;

public class FormUsersListBoundary implements Serializable {

	private class ViewableUser
	{
		private String username;
		private String firstname;
		private String lastname;
		private String email;
		private Integer id;
		
		public ViewableUser()
		{
			
		}

		public String getUsername() {
			return username;
		}

		public void setUsername(String username) {
			this.username = username;
		}

		public String getFirstname() {
			return firstname;
		}

		public void setFirstname(String firstname) {
			this.firstname = firstname;
		}

		public String getLastname() {
			return lastname;
		}

		public void setLastname(String lastname) {
			this.lastname = lastname;
		}

		public String getEmail() {
			return email;
		}

		public void setEmail(String email) {
			this.email = email;
		}

		public Integer getId() {
			return id;
		}

		public void setId(Integer id) {
			this.id = id;
		}
	}
	
	private ArrayList<ViewableUser> users;
	private Integer selectedUserID;
	
	private UserManagement ctrl;
	
	private ViewableUser createViewableFromUser(User user)
	{
		ViewableUser vUser = new ViewableUser();
		
		vUser.setId(user.getId());
		vUser.setFirstname(user.getFirstName());
		vUser.setLastname(user.getLastName());
		vUser.setUsername(user.getUsername());
		vUser.setEmail(user.getEmail());
		
		return vUser;
	}
	
	public FormUsersListBoundary() {
		this.users = new ArrayList<ViewableUser>();
	}

	public ArrayList<ViewableUser> getUsers() {
		return users;
	}

	public void setUsers(ArrayList<ViewableUser> users) {
		this.users = users;
	}

	public Integer getSelectedUserID() {
		return selectedUserID;
	}

	public void setSelectedUserID(Integer selectedUserID) {
		this.selectedUserID = selectedUserID;
	}
	
	public void updateUserList()
	{
		if(this.selectedUserID == null)
		{
			// do nothing
			return;
		}
		
		ArrayList<User> userList = null;
		
		try
		{
			userList = ctrl.getUserList(null);
		}
		catch(AdminManagementException ex)
		{
			this.sendMessage("Error", ex.getMessage(), FacesMessage.SEVERITY_ERROR);
		}
		
		this.users.clear();
		for(User user : userList)
		{
			this.users.add(this.createViewableFromUser(user));
		}
		
		
	}


	private void sendMessage(String summary, String detail, Severity severity)
	{
		FacesMessage message = new FacesMessage(summary, detail);
		message.setSeverity(severity);
		FacesContext context = FacesContext.getCurrentInstance();  
		context.addMessage(null, message);  
	}
}
